package org.jimmy.tang.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @author jimmy
 * 
 */
public class StringUtils {
    public static final String CHARSET_UTF8 = "UTF-8";
    private static final String CHARSET_GBK = "gbk";

    /**
     * 
     * @param str
     * @param newCharset
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String changeCharset(String str, String newCharset)
            throws UnsupportedEncodingException {
        if (str != null) {
            byte[] bs = str.getBytes();
            return new String(bs, newCharset);
        }
        return null;
    }

    /**
     * 
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String toUTF8(String str) throws UnsupportedEncodingException {
        return changeCharset(str, CHARSET_UTF8);
    }

    /**
     * 
     * @param bytes
     * @param offset
     * @param length
     * @return
     */
    public static String getGBKString(byte bytes[], int offset, int length) {
        return new String(bytes, offset, length, Charset.forName(CHARSET_GBK));
    }

    /**
     * 
     * @param str
     * @param oldCharset
     * @param newCharset
     * @return
     * @throws UnsupportedEncodingException
     */
    public String changeCharset(String str, String oldCharset, String newCharset)
            throws UnsupportedEncodingException {
        if (str != null) {
            byte[] bs = str.getBytes(oldCharset);
            return new String(bs, newCharset);
        }
        return null;
    }
}
